// 添加消息到聊天历史
export function appendMessage(message, isUser, chatHistory) {
  const messageDiv = document.createElement('div')
  messageDiv.className = `message ${isUser ? 'user-message' : 'ai-message'}`

  // 添加时间戳
  const timestamp = document.createElement('div')
  timestamp.className = 'timestamp'
  timestamp.textContent = new Date().toLocaleTimeString()

  // 渲染Markdown并处理代码块
  const formattedMessage = message.replace(/\n/g, '<br>')
  messageDiv.innerHTML = marked.parse(formattedMessage)

  // 添加复制按钮
  const copyBtn = document.createElement('button')
  copyBtn.className = 'copy-btn'
  copyBtn.textContent = '复制'
  copyBtn.onclick = () => {
    navigator.clipboard.writeText(message)
    copyBtn.textContent = '已复制!'
    setTimeout(() => (copyBtn.textContent = '复制'), 2000)
  }

  // 添加加载状态
  if (!isUser) {
    const loading = document.createElement('div')
    loading.className = 'loading'
    messageDiv.appendChild(loading)
    setTimeout(() => loading.remove(), 1000) // 模拟加载完成
  }

  messageDiv.appendChild(timestamp)
  messageDiv.appendChild(copyBtn)
  chatHistory.appendChild(messageDiv)
  chatHistory.scrollTop = chatHistory.scrollHeight

  // 保存消息到历史记录
  chrome.storage.local.get(['chatHistory'], (result) => {
    const history = result.chatHistory || []
    history.push({
      message: message,
      isUser: isUser,
      timestamp: new Date().toISOString(),
    })
    chrome.storage.local.set({ chatHistory: history })
  })
}

// 初始化聊天功能
export function setupChat(sendBtn, userInput, chatHistory, sendMessage) {
  // 发送按钮点击事件
  sendBtn.addEventListener('click', () => {
    const message = userInput.value.trim()
    if (message) {
      sendMessage(message)
      userInput.value = ''
    }
  })

  // 支持回车发送
  userInput.addEventListener('keypress', (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      sendBtn.click()
    }
  })

  // 加载历史记录
  chrome.storage.local.get(['chatHistory'], (result) => {
    const history = result.chatHistory || []
    history.forEach((item) => {
      appendMessage(item.message, item.isUser, chatHistory)
    })
  })

  // 清除历史记录
  document.getElementById('clearHistory').addEventListener('click', () => {
    if (confirm('确定要清除所有聊天记录吗？')) {
      chatHistory.innerHTML = ''
      chrome.storage.local.set({ chatHistory: [] })
    }
  })
}
